package com.house.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.house.entity.House;
import com.house.entity.Result;
import com.house.service.HouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/house")
public class HouseController {

    @Autowired
    private HouseService houseService;

    // 发布房源
    @PostMapping("/add")
    public Result addHouse(@RequestBody House house) {
        // 验证用户身份（只有房东可以发布）
        if (!"LANDLORD".equals(StpUtil.getSession().get("role"))) {
            return Result.error("无权限，只有房东可以发布房源");
        }

        house.setLandlordId(StpUtil.getLoginIdAsLong()); // 设置当前房东ID
        houseService.addHouse(house);
        return Result.success("房源发布成功");
    }

    // 编辑房源
    @PutMapping("/update")
    public Result updateHouse(@RequestBody House house) {
        house.setLandlordId(StpUtil.getLoginIdAsLong());
        houseService.updateHouse(house);
        return Result.success("房源信息更新成功");
    }

    // 删除房源
    @DeleteMapping("/delete/{id}")
    public Result deleteHouse(@PathVariable Long id) {
        Long landlordId = StpUtil.getLoginIdAsLong();
        houseService.deleteHouse(id, landlordId);
        return Result.success("房源删除成功");
    }

    // 查看房源列表
    @GetMapping("/list")
    public Result<List<House>> listHouses() {
        Long landlordId = StpUtil.getLoginIdAsLong();
        List<House> houses = houseService.getHousesByLandlord(landlordId);
        return Result.success(houses);
    }
}

